package com.billing.web.controller.attendance;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.billing.model.entity.ClocktimeAppBean;
import com.billing.model.entity.FillcardAppBean;
import com.billing.model.entity.LeaveAppBean;
import com.billing.model.entity.SchedulingAppBean;
import com.billing.model.entity.TAttendance;
import com.billing.model.entity.TAttendanceAppBean;
import com.billing.model.entity.TAttendanceReport;
import com.billing.model.entity.TClocktime;
import com.billing.model.entity.TDept;
import com.billing.model.entity.TFillcard;
import com.billing.model.entity.TLeave;
import com.billing.model.entity.TSchedulingdetails;
import com.billing.model.entity.TShift;
import com.billing.model.entity.TUser;
import com.billing.service.AttendanceService;
import com.billing.service.DeptService;
import com.billing.service.FillcardService;
import com.billing.service.LeaveService;
import com.billing.service.SchedulingdetailsService;
import com.billing.service.ShiftPunchtimeService;
import com.billing.service.ShiftService;
import com.billing.service.UserService;
import com.billing.utils.DateUtil;
import com.billing.utils.ExcelUtil;

import net.sf.json.JSONObject;

/**
 * 考勤信息
 * @author Administrator
 *
 */
@RequestMapping(value="/attendance")
@Controller
public class AttendanceController {

	@Resource
	private AttendanceService attendanceService;
	@Resource
	private UserService userService;
	@Resource
	private ShiftService shiftService;
	@Resource
	private ShiftPunchtimeService shiftPunchtimeService;
	@Resource
	private SchedulingdetailsService schedulingdetailsService;
	@Resource
	private DeptService deptService;
	@Resource
	private FillcardService fillcardService;
	@Resource
	private LeaveService leaveService;
	
	
	SimpleDateFormat mdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	/**
	 * 获取考勤列表信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/index",method=RequestMethod.GET)
	public String index(HttpServletRequest request, Model model){
		String name = request.getParameter("name");
		String dept = request.getParameter("dept");
		String jobnumber = request.getParameter("jobnumber");
		int pageSize = 10;
		String fromDateStr = request.getParameter("fromDate");
		String endDateStr = request.getParameter("endDate");
		try {
			if (dept!=null&&dept.length() > 0) {
				dept = URLDecoder.decode(URLDecoder.decode(dept, "UTF-8"),"UTF-8");
			}
			if (name!=null&&name.length() > 0) {
				name = URLDecoder.decode(URLDecoder.decode(name, "UTF-8"),"UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
		}
		List<TDept> deptlist=deptService.getTDeptlist();
		request.setAttribute("fromDate", fromDateStr);
		request.setAttribute("endDate", endDateStr);
		request.setAttribute("name", name);
		request.setAttribute("dept", dept);
		request.setAttribute("jobnumber", jobnumber);
		request.setAttribute("deptlist", deptlist);
		Long starttime = 0l;
		Long endtime = 0l;
		Date startDate = null;
		Date endDate = null;
		try {
			fromDateStr+=" 00:00:00";
			endDateStr+=" 23:59:59";
			startDate = mdf.parse(fromDateStr);
			endDate = mdf.parse(endDateStr);
			starttime=startDate.getTime();
			endtime=endDate.getTime();
		} catch (Exception e) {
		}
		// 获取当前页数
		int currentPage = 1;
		try {
			currentPage = new Integer(request.getParameter("currentPage"));
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		int organizationid=(int) request.getSession().getAttribute("organizationid");
		int totalNum = attendanceService.selectTAttendanceNum(name, dept, starttime, endtime,jobnumber,organizationid);
		int totalPage = totalNum / pageSize;
		if (totalNum % pageSize != 0) {
			totalPage++;	
		}
		totalPage = totalPage <= 0 ? 1 : totalPage;
		currentPage = currentPage > totalPage ? totalPage : currentPage;
		List<TAttendance> list=attendanceService.selectTAttendanceList(name, dept, starttime, endtime,jobnumber,organizationid, (currentPage - 1) * pageSize, pageSize);
		request.setAttribute("totalNum", totalNum);
		request.setAttribute("list", list);
		request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalNum", totalNum);
        request.setAttribute("totalPage", totalPage);
		return "attendance/index";
	}
	
	
	//导出用户信息
	@RequestMapping("export")  
	public void exportInof(HttpServletRequest request,HttpServletResponse response) throws Exception{  
	    response.setContentType("application/vnd.ms-excel");  
	    String filename="考勤报表.xls";
	    filename = new String(filename.getBytes(), "ISO-8859-1");
	    response.setHeader("Content-Disposition", "attachment; filename="+filename);  
	    OutputStream out = response.getOutputStream();  
	    String name = request.getParameter("name");
	    String dept = request.getParameter("dept");
		String jobnumber = request.getParameter("jobnumber");
		int pageSize = 10;
		String fromDateStr = request.getParameter("fromDate");
		String endDateStr = request.getParameter("endDate");
		try {
			if (dept!=null&&dept.length() > 0) {
				dept = URLDecoder.decode(URLDecoder.decode(dept, "UTF-8"),"UTF-8");
			}
			if (name!=null&&name.length() > 0) {
				name = URLDecoder.decode(URLDecoder.decode(name, "UTF-8"),"UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
		}
		List<TDept> deptlist=deptService.getTDeptlist();
		request.setAttribute("fromDate", fromDateStr);
		request.setAttribute("endDate", endDateStr);
		request.setAttribute("name", name);
		request.setAttribute("dept", dept);
		request.setAttribute("jobnumber", jobnumber);
		request.setAttribute("deptlist", deptlist);
		Long starttime = 0l;
		Long endtime = 0l;
		Date startDate = null;
		Date endDate = null;
		try {
			fromDateStr+=" 00:00:00";
			endDateStr+=" 23:59:59";
			startDate = mdf.parse(fromDateStr);
			endDate = mdf.parse(endDateStr);
			starttime=startDate.getTime();
			endtime=endDate.getTime();
		} catch (Exception e) {
		}
		// 获取当前页数
		int currentPage = 1;
		try {
			currentPage = new Integer(request.getParameter("currentPage"));
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		int organizationid=(int) request.getSession().getAttribute("organizationid");
		int totalNum = attendanceService.selectTAttendanceNum(name, dept, starttime, endtime,jobnumber,organizationid);
		int totalPage = totalNum / pageSize;
		if (totalNum % pageSize != 0) {
			totalPage++;	
		}
		totalPage = totalPage <= 0 ? 1 : totalPage;
		currentPage = currentPage > totalPage ? totalPage : currentPage;
		List<TAttendance> list=attendanceService.selectTAttendanceList(name, dept, starttime, endtime,jobnumber,organizationid, (currentPage - 1) * pageSize, pageSize);
		List<TAttendanceReport> replist=new ArrayList<TAttendanceReport>();
		for (TAttendance att : list) {
			TAttendanceReport rep=new TAttendanceReport();
			rep.setUsername(att.getUser().getName());
			if(att.getStarttime1()!=null){
				rep.setStarttime1(DateUtil.getStringFormat(att.getStarttime1(),"yyyy-MM-dd hh:mm:ss"));
			}
			if(att.getEndtime1()!=null){
				rep.setEndtime1(DateUtil.getStringFormat(att.getEndtime1(),"yyyy-MM-dd hh:mm:ss"));
			}
			if(att.getStarttime2()!=null){
				rep.setStarttime2(DateUtil.getStringFormat(att.getStarttime2(),"yyyy-MM-dd hh:mm:ss"));
			}
			if(att.getEndtime2()!=null){
				rep.setEndtime2(DateUtil.getStringFormat(att.getEndtime2(),"yyyy-MM-dd hh:mm:ss"));
			}
			if(att.getStarttime3()!=null){
				rep.setStarttime3(DateUtil.getStringFormat(att.getStarttime3(),"yyyy-MM-dd hh:mm:ss"));
			}
			if(att.getEndtime3()!=null){
				rep.setEndtime3(DateUtil.getStringFormat(att.getEndtime3(),"yyyy-MM-dd hh:mm:ss"));
			}
			rep.setLatetime(att.getLatetime());
			rep.setEarlytime(att.getEarlytime());
			rep.setResults1(att.getResults1());
			rep.setResults2(att.getResults2());
			rep.setResults3(att.getResults3());
			rep.setResults4(att.getResults4());
			rep.setResults5(att.getResults5());
			rep.setResults6(att.getResults6());
			rep.setAddress1(att.getAddress1());
			rep.setAddress2(att.getAddress2());
			rep.setAddress3(att.getAddress3());
			rep.setAddress4(att.getAddress4());
			rep.setAddress5(att.getAddress5());
			rep.setAddress6(att.getAddress6());
			rep.setWorkingtime(att.getWorkingtime());
			if(att.getCreatetime()!=null){
				rep.setCreatetime(DateUtil.getStringFormat(att.getCreatetime(),"yyyy-MM-dd"));
			}
			replist.add(rep);
		}
		ExcelUtil<TAttendanceReport> t=new ExcelUtil<TAttendanceReport>();
		String [] headers={"姓名","上班打卡时间","下班打卡时间","上班打卡时间","下班打卡时间","上班打卡时间","下班打卡时间","迟到总分钟","早退总分钟",
				"迟到分钟1","迟到分钟2","迟到分钟3","迟到分钟4","迟到分钟5","迟到分钟6","打卡地区1","打卡地区2","打卡地区3","打卡地区4","打卡地区5",
				"打卡地区6","工作时长","考勤日期"};  
		t.exportExcel("sheet名称", headers, replist, out, "yyyy-MM-dd HH:mm:ss");
		}
	
	
	/**
	 * 修改考勤记录
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/update",method=RequestMethod.GET)
	public String update(HttpServletRequest request, Model model){
		String id = request.getParameter("id");
		TAttendance atten=attendanceService.selectTAttendanceId(id);
		request.setAttribute("atten", atten);
		return "attendance/updateAttendance";
	}
	
	/**
	 * 修改考勤记录
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/updateAttendance",method=RequestMethod.POST)
	public String updateAttendance(HttpServletRequest request, Model model){
		String id = request.getParameter("id");
		TAttendance atten=attendanceService.selectTAttendanceId(id);
		if(atten!=null){
			atten.setLatetime(0);
			atten.setEarlytime(0);
			atten.setResults1(0);
			atten.setResults2(0);
			atten.setResults3(0);
			atten.setResults4(0);
			atten.setResults5(0);
			atten.setResults6(0);
			int msg=attendanceService.updateTAttendance(atten);
			request.setAttribute("msg", msg);
		}else{
			request.setAttribute("msg", 0);
		}
		request.setAttribute("atten", atten);
		return "attendance/updateAttendance";
	}
	
	/**
	 * APP获取打卡信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getClockin", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String getClockin(HttpServletRequest request, Model model) {
		String msg=null;
		JSONObject jsonObject = null;
		String id =null;//用户id
		String json = request.getParameter("json");
		try {
			json = java.net.URLDecoder.decode(json,"UTF-8");
	    } catch (UnsupportedEncodingException e1) {
	    	e1.printStackTrace();
	    }
		jsonObject = JSONObject.fromObject(json);
		try{
			id =jsonObject.getString("userid");
		}catch(Exception e){
            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		try {
			TUser user=userService.selectTUserId(id);
			//获取当前时间
			Long currenttime=System.currentTimeMillis();
			//获取排班打卡时间
			int year=DateUtil.getYear();
			int month=DateUtil.getMonth();
			int date=DateUtil.getDate();
			int LastDay=0;
			int LastMonth=0;
			int LastYear=0;
			if(date!=1){
				LastDay=date-1;
				LastMonth=month;
				LastYear=year;
			}else{//获取上个月最后一天日期
				LastDay=DateUtil.getLastDay();
				LastMonth=DateUtil.getLastMonth();
				LastYear=DateUtil.getLastYear();
			}
			int dd=0;//公用参数
			long time=0l;//公用参数
			String timeformat=year+"-"+month+"-"+date;
			long data=DateUtil.getStringTime(timeformat, "yyyy-MM-dd");
			long start=DateUtil.getStartTime(0,data).getTime();
			long end=DateUtil.getnowEndTime(23,data).getTime();
			TAttendance attendance=new TAttendance();
			Map<String, Object> datemap=new HashMap<String, Object>();
			Map<String, Object> map=new HashMap<String, Object>();
			SchedulingAppBean sappbean=new SchedulingAppBean();
			TAttendanceAppBean appbean=new TAttendanceAppBean();
			List<FillcardAppBean> filist=new ArrayList<FillcardAppBean>();
			List<TFillcard> fillist=new ArrayList<TFillcard>();
			if(user.getSchedulingId()!=null){
				//获取前一天排班日期和打卡时间
				TSchedulingdetails shebefore=schedulingdetailsService.getTSchedulingdetailsDesc(LastYear, LastMonth, LastDay,user.getSchedulingId());
				//获取今天排班日期和打卡时间
				TSchedulingdetails sheToday=schedulingdetailsService.getTSchedulingdetailsAsc(year, month, date,user.getSchedulingId());
				//获取班次信息
				List<TShift> shiftlist=shiftService.selectTShiftList(user.getOrganizationId(),0,999);
				//获取请假信息
				List<TLeave> leavelist=leaveService.getTLeaveList(start, end, user.getId());
				if(shiftlist!=null&&shiftlist.size()>0){
					if(shebefore!=null){
						if(shebefore.getClolist()!=null&&shebefore.getClolist().size()>0){
							for (TShift shift : shiftlist) {
								if(shebefore.getShiftId()==shift.getId()){
									sappbean.setStartduration(shift.getStartduration());
									sappbean.setEndduration(shift.getEndduration());
								}
							}
							dd=DateUtil.getDay(shebefore.getClolist().get(0).getTime());
							if(dd==date){//前一天包含今天打卡日期
								if(sheToday!=null){
									if(sheToday.getClolist()!=null&&sheToday.getClolist().size()>0){//获取今天日期打卡最早时间
										int startduration=0;
										for (TShift shift : shiftlist) {
											if(sheToday.getShiftId()==shift.getId()){
												startduration=Integer.valueOf(shift.getStartduration());
											}
										}
										time=sheToday.getClolist().get(0).getTime()-startduration*60*1000;
										if(time>currenttime){//获取前一天考勤记录返回
											Long starttime=DateUtil.getStartTime(-24).getTime();
											Long endtime=DateUtil.getnowEndTime(-1).getTime();
											attendance=attendanceService.selectTAttendanceById(user.getId(), starttime, endtime);
											if(attendance!=null){
												BeanUtils.copyProperties(appbean,attendance);
												//获取用户补卡审批单信息
												fillist=fillcardService.getTFillcardListByAttid(user.getId(), appbean.getId(),start,end);
												if(fillist==null||fillist.size()==0){
													fillist=fillcardService.getTFillcardListByAttid(user.getId(), 0,start,end);
												}
												setTFillcard(fillist,filist);
											}else{
												fillist=fillcardService.getTFillcardListByAttid(user.getId(), 0,start,end);
												String filltime=null;
												String dataary=DateUtil.getStringFormat(data,"yyyy-MM-dd");
												List<TFillcard> fillistary=new ArrayList<TFillcard>();
												for (TFillcard fil : fillist) {
													filltime=DateUtil.getStringFormat(fil.getFilltime(),"yyyy-MM-dd");
													if(dataary.equals(filltime)){
														fillistary.add(fil);
													}
												}
												setTFillcard(fillistary,filist);
											}
											setFillstatus(currenttime, sheToday.getClolist(), attendance,filist);
											appbean.setFilist(filist);
											sappbean.setAttendance(appbean);
											ClocktimeAppBean clockt=null;
											for (TClocktime clo : shebefore.getClolist()) {
												clockt=new ClocktimeAppBean();
												BeanUtils.copyProperties(clockt, clo);
												sappbean.getClocktime().add(clockt);
												setLesveAttendance(clo, leavelist, appbean);
											}
											sappbean.setLat(shebefore.getShe().getLat());
											sappbean.setLon(shebefore.getShe().getLon());
											sappbean.setName(shebefore.getShe().getName());
											sappbean.setDetailsid(shebefore.getId());
											datemap.put("code", "1");
										}else{//获取今天考勤记录返回
											Long starttime=DateUtil.getStartTime(0).getTime();
											Long endtime=DateUtil.getnowEndTime(23).getTime();
											attendance=attendanceService.selectTAttendanceById(user.getId(), starttime, endtime);
											if(attendance!=null){
												BeanUtils.copyProperties(appbean,attendance);
												//获取用户补卡审批单信息
												fillist=fillcardService.getTFillcardListByAttid(user.getId(), appbean.getId(),start,end);
												if(fillist==null||fillist.size()==0){
													fillist=fillcardService.getTFillcardListByAttid(user.getId(), 0,start,end);
												}
												setTFillcard(fillist,filist);
											}else{
												fillist=fillcardService.getTFillcardListByAttid(user.getId(), 0,start,end);
												String filltime=null;
												String dataary=DateUtil.getStringFormat(data,"yyyy-MM-dd");
												List<TFillcard> fillistary=new ArrayList<TFillcard>();
												for (TFillcard fil : fillist) {
													filltime=DateUtil.getStringFormat(fil.getFilltime(),"yyyy-MM-dd");
													if(dataary.equals(filltime)){
														fillistary.add(fil);
													}
												}
												setTFillcard(fillistary,filist);
											}
											setFillstatus(currenttime, sheToday.getClolist(), attendance, filist);
											appbean.setFilist(filist);
											sappbean.setAttendance(appbean);
											ClocktimeAppBean clockt=null;
											for (TClocktime clo : sheToday.getClolist()) {
												clockt=new ClocktimeAppBean();
												BeanUtils.copyProperties(clockt, clo);
												sappbean.getClocktime().add(clockt);
												setLesveAttendance(clo, leavelist, appbean);
											}
											sappbean.setLat(sheToday.getShe().getLat());
											sappbean.setLon(sheToday.getShe().getLon());
											sappbean.setName(sheToday.getShe().getName());
											sappbean.setDetailsid(sheToday.getId());
											datemap.put("code", "1");
										}
									}else{//该日期没有考勤信息
										map.put("attendance", null);
										datemap.put("code", "1");
									}
								}else{//该日期没有考勤信息
									map.put("attendance", null);
									datemap.put("code", "1");
								}
							}else{//不包含获取今天考勤记录返回
								Long starttime=DateUtil.getStartTime(0).getTime();
								Long endtime=DateUtil.getnowEndTime(23).getTime();
								attendance=attendanceService.selectTAttendanceById(user.getId(), starttime, endtime);
								if(attendance!=null){
									BeanUtils.copyProperties(appbean,attendance);
									//获取用户补卡审批单信息
									fillist=fillcardService.getTFillcardListByAttid(user.getId(), appbean.getId(),start,end);
									if(fillist==null||fillist.size()==0){
										fillist=fillcardService.getTFillcardListByAttid(user.getId(), 0,start,end);
									}
									setTFillcard(fillist,filist);
								}else{
									fillist=fillcardService.getTFillcardListByAttid(user.getId(), 0,start,end);
									String filltime=null;
									String dataary=DateUtil.getStringFormat(data,"yyyy-MM-dd");
									List<TFillcard> fillistary=new ArrayList<TFillcard>();
									for (TFillcard fil : fillist) {
										filltime=DateUtil.getStringFormat(fil.getFilltime(),"yyyy-MM-dd");
										if(dataary.equals(filltime)){
											fillistary.add(fil);
										}
									}
									setTFillcard(fillistary,filist);
								}
								setFillstatus(currenttime, sheToday.getClolist(), attendance, filist);
								appbean.setFilist(filist);
								sappbean.setAttendance(appbean);
								ClocktimeAppBean clockt=null;
								for (TClocktime clo : sheToday.getClolist()) {
									clockt=new ClocktimeAppBean();
									BeanUtils.copyProperties(clockt, clo);
									sappbean.getClocktime().add(clockt);
									setLesveAttendance(clo, leavelist, appbean);
								}
								sappbean.setLat(sheToday.getShe().getLat());
								sappbean.setLon(sheToday.getShe().getLon());
								sappbean.setName(sheToday.getShe().getName());
								sappbean.setDetailsid(sheToday.getId());
								datemap.put("code", "1");
							}
						}else{//该日期没有考勤信息
							map.put("attendance", null);
							datemap.put("code", "1");
						}
					}else if(sheToday!=null){
						if(sheToday.getClolist()!=null&&sheToday.getClolist().size()>0){//获取今天日期打卡最早时间
							int startduration=0;
							for (TShift shift : shiftlist) {
								if(sheToday.getShiftId()==shift.getId()){
									startduration=Integer.valueOf(shift.getStartduration());
								}
							}
							time=sheToday.getClolist().get(0).getTime()-startduration*60*1000;
							if(time>currenttime){//获取前一天考勤记录返回
								Long starttime=DateUtil.getStartTime(-24).getTime();
								Long endtime=DateUtil.getnowEndTime(-1).getTime();
								attendance=attendanceService.selectTAttendanceById(user.getId(), starttime, endtime);
								if(attendance!=null){
									BeanUtils.copyProperties(appbean,attendance);
									//获取用户补卡审批单信息
									fillist=fillcardService.getTFillcardListByAttid(user.getId(), appbean.getId(),start,end);
									if(fillist==null||fillist.size()==0){
										fillist=fillcardService.getTFillcardListByAttid(user.getId(), 0,start,end);
									}
									setTFillcard(fillist,filist);
								}else{
									fillist=fillcardService.getTFillcardListByAttid(user.getId(), 0,start,end);
									String filltime=null;
									String dataary=DateUtil.getStringFormat(data,"yyyy-MM-dd");
									List<TFillcard> fillistary=new ArrayList<TFillcard>();
									for (TFillcard fil : fillist) {
										filltime=DateUtil.getStringFormat(fil.getFilltime(),"yyyy-MM-dd");
										if(dataary.equals(filltime)){
											fillistary.add(fil);
										}
									}
									setTFillcard(fillistary,filist);
								}
								setFillstatus(currenttime, sheToday.getClolist(), attendance,filist);
								appbean.setFilist(filist);
								sappbean.setAttendance(appbean);
								ClocktimeAppBean clockt=null;
								for (TClocktime clo : shebefore.getClolist()) {
									clockt=new ClocktimeAppBean();
									BeanUtils.copyProperties(clockt, clo);
									sappbean.getClocktime().add(clockt);
									setLesveAttendance(clo, leavelist, appbean);
								}
								sappbean.setLat(shebefore.getShe().getLat());
								sappbean.setLon(shebefore.getShe().getLon());
								sappbean.setName(shebefore.getShe().getName());
								sappbean.setDetailsid(shebefore.getId());
								datemap.put("code", "1");
							}else{//获取今天考勤记录返回
								Long starttime=DateUtil.getStartTime(0).getTime();
								Long endtime=DateUtil.getnowEndTime(23).getTime();
								attendance=attendanceService.selectTAttendanceById(user.getId(), starttime, endtime);
								if(attendance!=null){
									BeanUtils.copyProperties(appbean,attendance);
									//获取用户补卡审批单信息
									fillist=fillcardService.getTFillcardListByAttid(user.getId(), appbean.getId(),start,end);
									if(fillist==null||fillist.size()==0){
										fillist=fillcardService.getTFillcardListByAttid(user.getId(), 0,start,end);
									}
									setTFillcard(fillist,filist);
								}else{
									fillist=fillcardService.getTFillcardListByAttid(user.getId(), 0,start,end);
									String filltime=null;
									String dataary=DateUtil.getStringFormat(data,"yyyy-MM-dd");
									List<TFillcard> fillistary=new ArrayList<TFillcard>();
									for (TFillcard fil : fillist) {
										filltime=DateUtil.getStringFormat(fil.getFilltime(),"yyyy-MM-dd");
										if(dataary.equals(filltime)){
											fillistary.add(fil);
										}
									}
									setTFillcard(fillistary,filist);
								}
								setFillstatus(currenttime, sheToday.getClolist(), attendance, filist);
								appbean.setFilist(filist);
								sappbean.setAttendance(appbean);
								ClocktimeAppBean clockt=null;
								for (TClocktime clo : sheToday.getClolist()) {
									clockt=new ClocktimeAppBean();
									BeanUtils.copyProperties(clockt, clo);
									sappbean.getClocktime().add(clockt);
									setLesveAttendance(clo, leavelist, appbean);
								}
								sappbean.setLat(sheToday.getShe().getLat());
								sappbean.setLon(sheToday.getShe().getLon());
								sappbean.setName(sheToday.getShe().getName());
								sappbean.setDetailsid(sheToday.getId());
								datemap.put("code", "1");
							}
						}else{//该日期没有考勤信息
							map.put("attendance", null);
							datemap.put("code", "1");
						}
					}else{//该日期没有考勤信息
						map.put("attendance", null);
						datemap.put("code", "1");
					}
				}else{//无班次记录
					map.put("attendance", null);
					datemap.put("code", "1");
				}
			}else{
				map.put("attendance", null);
				datemap.put("code", "1");
			}
			datemap.put("data", sappbean);
			JSONObject jsons = JSONObject.fromObject(datemap);
			msg=jsons.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msg;
	}
	
	/**
	 * 封装补卡信息
	 * @param currenttime系统时间
	 * @param clolist
	 * @param attendance
	 */
	public void setFillstatus(Long currenttime,List<TClocktime> clolist,TAttendance attendance,
			List<FillcardAppBean> filist){
		int status=0;
		int mapid=0;
		if(attendance!=null){
			FillcardAppBean bean=new FillcardAppBean();
			if(attendance.getStarttime1()!=null&&attendance.getStarttime1()>0){
				if(filist!=null&&filist.size()>0){
					for (FillcardAppBean map : filist) {
						if(map.getId()==1){
							if(attendance.getResults1()>0){
								map.setFillstatus(1);
							}else{
								map.setFillstatus(0);
							}
						}
					}
				}else{
					bean=new FillcardAppBean();
					bean.setId(1);
					if(attendance.getResults1()>0){
						bean.setFillstatus(1);
					}else{
						bean.setFillstatus(0);
					}
					filist.add(bean);
				}
			}
			if(attendance.getEndtime1()!=null&&attendance.getEndtime1()>0){
				if(filist!=null&&filist.size()>0){
					for (FillcardAppBean map : filist) {
						if(map.getId()==2){
							if(attendance.getResults2()>0){
								map.setFillstatus(1);
							}else{
								map.setFillstatus(0);
							}
						}
					}
				}else{
					bean=new FillcardAppBean();
					bean.setId(2);
					if(attendance.getResults2()>0){
						bean.setFillstatus(1);
					}else{
						bean.setFillstatus(0);
					}
					filist.add(bean);
				}
			}
			if(attendance.getStarttime2()!=null&&attendance.getStarttime2()>0){
				if(filist!=null&&filist.size()>0){
					for (FillcardAppBean map : filist) {
						if(map.getId()==3){
							if(attendance.getResults3()>0){
								map.setFillstatus(1);
							}else{
								map.setFillstatus(0);
							}
						}
					}
				}else{
					bean=new FillcardAppBean();
					bean.setId(3);
					if(attendance.getResults3()>0){
						bean.setFillstatus(1);
					}else{
						bean.setFillstatus(0);
					}
					filist.add(bean);
				}
			}
			if(attendance.getEndtime2()!=null&&attendance.getEndtime2()>0){
				if(filist!=null&&filist.size()>0){
					for (FillcardAppBean map : filist) {
						if(map.getId()==4){
							if(attendance.getResults4()>0){
								map.setFillstatus(1);
							}else{
								map.setFillstatus(0);
							}
						}
					}
				}else{
					bean=new FillcardAppBean();
					bean.setId(4);
					if(attendance.getResults4()>0){
						bean.setFillstatus(1);
					}else{
						bean.setFillstatus(0);
					}
					filist.add(bean);
				}
			}
			if(attendance.getStarttime3()!=null&&attendance.getStarttime3()>0){
				if(filist!=null&&filist.size()>0){
					for (FillcardAppBean map : filist) {
						if(map.getId()==5){
							if(attendance.getResults5()>0){
								map.setFillstatus(1);
							}else{
								map.setFillstatus(0);
							}
						}
					}
				}else{
					bean=new FillcardAppBean();
					bean.setId(5);
					if(attendance.getResults5()>0){
						bean.setFillstatus(1);
					}else{
						bean.setFillstatus(0);
					}
					filist.add(bean);
				}
			}
			if(attendance.getEndtime3()!=null&&attendance.getEndtime3()>0){
				if(filist!=null&&filist.size()>0){
					for (FillcardAppBean map : filist) {
						if(map.getId()==6){
							if(attendance.getResults6()>0){
								map.setFillstatus(1);
							}else{
								map.setFillstatus(0);
							}
						}
					}
				}else{
					bean=new FillcardAppBean();
					bean.setId(6);
					if(attendance.getResults6()>0){
						bean.setFillstatus(1);
					}else{
						bean.setFillstatus(0);
					}
					filist.add(bean);
				}
			}
			for (FillcardAppBean map : filist) {
				mapid=map.getId();
				if(mapid==1){
					if(attendance.getStarttime1()!=null&&attendance.getStarttime1()>0){
						if(attendance.getResults1()>0){
							map.setFillstatus(1);
						}else{
							map.setFillstatus(0);
						}
					}else{
						status=getTClocktime(clolist, 1, currenttime, 1,attendance);
						map.setFillstatus(status);
					}
				}
				if(mapid==2){
					if(attendance.getEndtime1()!=null&&attendance.getEndtime1()>0){
						if(attendance.getResults2()>0){
							map.setFillstatus(1);
						}else{
							map.setFillstatus(0);
						}
					}else{
						status=getTClocktime(clolist, 2, currenttime, 2,attendance);
						map.setFillstatus(status);
					}
				}
				if(mapid==3){
					if(attendance.getStarttime2()!=null&&attendance.getStarttime2()>0){
						if(attendance.getResults3()>0){
							map.setFillstatus(1);
						}else{
							map.setFillstatus(0);
						}
					}else{
						status=getTClocktime(clolist, 3, currenttime, 1,attendance);
						map.setFillstatus(status);
					}
				}
				if(mapid==4){
					if(attendance.getEndtime2()!=null&&attendance.getEndtime2()>0){
						if(attendance.getResults4()>0){
							map.setFillstatus(1);
						}else{
							map.setFillstatus(0);
						}
					}else{
						status=getTClocktime(clolist, 4, currenttime, 2,attendance);
						map.setFillstatus(status);
					}
				}
				if(mapid==5){
					if(attendance.getStarttime3()!=null&&attendance.getStarttime3()>0){
						if(attendance.getResults5()>0){
							map.setFillstatus(1);
						}else{
							map.setFillstatus(0);
						}
					}else{
						status=getTClocktime(clolist, 5, currenttime, 1,attendance);
						map.setFillstatus(status);
					}
				}
				if(mapid==6){
					if(attendance.getEndtime3()!=null&&attendance.getEndtime3()>0){
						if(attendance.getResults6()>0){
							map.setFillstatus(1);
						}else{
							map.setFillstatus(0);
						}
					}else{
						status=getTClocktime(clolist, 6, currenttime, 2,attendance);
						map.setFillstatus(status);
					}
				}
			}
			getFillcardAppBean(currenttime, filist, clolist,attendance);
		}else{
			getFillcardAppBean(currenttime, filist, clolist,attendance);
			for (FillcardAppBean map : filist) {
				mapid=map.getId();
				if(mapid==1){
					map.setFillstatus(getTClocktime(clolist, 1, currenttime, 1,attendance));
				}
				if(mapid==2){
					map.setFillstatus(getTClocktime(clolist, 2, currenttime, 2,attendance));
				}
				if(mapid==3){
					map.setFillstatus(getTClocktime(clolist, 3, currenttime, 1,attendance));
				}
				if(mapid==4){
					map.setFillstatus(getTClocktime(clolist, 4, currenttime, 2,attendance));
				}
				if(mapid==5){
					map.setFillstatus(getTClocktime(clolist, 5, currenttime, 1,attendance));
				}
				if(mapid==6){
					map.setFillstatus(getTClocktime(clolist, 6, currenttime, 2,attendance));
				}
			}
		}
	}
	
	public void getFillcardAppBean(Long currenttime,List<FillcardAppBean> filist,List<TClocktime> clolist,TAttendance attendance){
		if(filist!=null&&filist.size()>0){
			boolean fale=true;
			FillcardAppBean fill=new FillcardAppBean();
			int type=1;
			for (int i = 1; i < clolist.size()+1; i++) {
				fale=true;
				fill=new FillcardAppBean();
				fill.setId(i);
				if(i%2==0){
					type=2;
				}else{
					type=1;
				}
				fill.setFillstatus(getTClocktime(clolist, i, currenttime, type,attendance));
				for (FillcardAppBean fil : filist) {
					if(fil.getId()==fill.getId()){
						fale=false;
					}
				}
				if(fale){
					filist.add(fill);
				}
			}
		}else{
			FillcardAppBean fill=new FillcardAppBean();
			fill.setId(1);
			fill.setFillstatus(getTClocktime(clolist, 1, currenttime, 1,attendance));
			filist.add(fill);
			fill=new FillcardAppBean();
			fill.setId(2);
			fill.setFillstatus(getTClocktime(clolist, 2, currenttime, 2,attendance));
			filist.add(fill);
			fill=new FillcardAppBean();
			fill.setId(3);
			fill.setFillstatus(getTClocktime(clolist, 3, currenttime, 1,attendance));
			filist.add(fill);
			fill=new FillcardAppBean();
			fill.setId(4);
			fill.setFillstatus(getTClocktime(clolist, 4, currenttime, 2,attendance));
			filist.add(fill);
			fill=new FillcardAppBean();
			fill.setId(5);
			fill.setFillstatus(getTClocktime(clolist, 5, currenttime, 1,attendance));
			filist.add(fill);
			fill=new FillcardAppBean();
			fill.setId(6);
			fill.setFillstatus(getTClocktime(clolist, 6, currenttime, 2,attendance));
			filist.add(fill);
		}
	}
	
	
	
	/**
	 * 匹配是否补卡
	 * @param clolist
	 * @param sort
	 * @param currenttime 系统时间
	 * @param type
	 * @return
	 */
	public int getTClocktime(List<TClocktime> clolist,int sort,Long currenttime,int type,TAttendance attendance){
		if(type==1){
			for (TClocktime clo : clolist) {
				if(clo.getSort()==sort){
					if(attendance!=null){
						if(sort==1&&attendance.getStarttime1()!=null){
							if(attendance.getStarttime1()>clo.getTime()){
								return 1;
							}else{
								return 0;
							}
						}else if(sort==2&&attendance.getEndtime1()!=null){
							if(attendance.getEndtime1()>clo.getTime()){
								return 0;
							}
						}else if(sort==3&&attendance.getStarttime2()!=null){
							if(attendance.getStarttime2()>clo.getTime()){
								return 1;
							}else{
								return 0;
							}
						}else if(sort==4&&attendance.getEndtime2()!=null){
							if(attendance.getEndtime2()>clo.getTime()){
								return 0;
							}
						}else if(sort==5&&attendance.getStarttime3()!=null){
							if(attendance.getStarttime3()>clo.getTime()){
								return 1;
							}else{
								return 0;
							}
						}else if(sort==6&&attendance.getEndtime3()!=null){
							if(attendance.getEndtime3()>clo.getTime()){
								return 0;
							}
						}else if(currenttime>clo.getTime()){
							return 1;
						}else{
							return 0;
						}
					}else{
						if(currenttime>clo.getTime()+7200000){
							return 1;
						}else{
							return 0;
						}
					}
				}
			}
		}else{
			boolean fal=true;
			for (TClocktime clo : clolist) {
				if(clo.getSort()==sort){
					if(attendance!=null){
						if(sort==1&&attendance.getStarttime1()!=null){
							if(attendance.getStarttime1()>clo.getTime()){
								return 1;
							}else{
								return 0;
							}
						}else if(sort==2&&attendance.getEndtime1()!=null){
							if(attendance.getEndtime1()>clo.getTime()){
								return 0;
							}
						}else if(sort==3&&attendance.getStarttime2()!=null){
							if(attendance.getStarttime2()>clo.getTime()){
								return 1;
							}else{
								return 0;
							}
						}else if(sort==4&&attendance.getEndtime2()!=null){
							if(attendance.getEndtime2()>clo.getTime()){
								return 0;
							}
						}else if(sort==5&&attendance.getStarttime3()!=null){
							if(attendance.getStarttime3()>clo.getTime()){
								return 1;
							}else{
								return 0;
							}
						}else if(sort==6&&attendance.getEndtime3()!=null){
							if(attendance.getEndtime3()>clo.getTime()){
								return 0;
							}
						}else{
							return 0;
						}
					}else{
						String time=DateUtil.getStringFormat(clo.getTime());
						String curtime=DateUtil.getStringFormat(currenttime);
						if(time.equals(curtime)){
							return 0;
						}else{
							return 1;
						}
					}
				}
			}
			if(fal){
				for (TClocktime clo : clolist) {
					if(clo.getSort()==sort){
						String time=DateUtil.getStringFormat(clo.getTime());
						String curtime=DateUtil.getStringFormat(currenttime);
						if(time.equals(curtime)){
							return 0;
						}else{
							return 1;
						}
					}
				}
			}
		}
		return 0;
	}
	
	
	/**
	 * 封装审批状态
	 * @param fillist
	 * @param appbean
	 */
	public void setTFillcard(List<TFillcard> fillist,List<FillcardAppBean> filist){
		FillcardAppBean bean=new FillcardAppBean();
		for (TFillcard fil : fillist) {
			bean=new FillcardAppBean();
			if(fil.getType()==1){
				if(fil.getStatus()==1){
					bean.setStatus(fil.getStatus());
				}else{
					if(fil.getPassstatus()==1){
						bean.setStatus(2);
					}else{
						bean.setStatus(3);
					}
				}
				bean.setMaiid(fil.getMaiid());
				bean.setId(1);
				filist.add(bean);
			}else if(fil.getType()==2){
				if(fil.getStatus()==1){
					bean.setStatus(fil.getStatus());
				}else{
					if(fil.getPassstatus()==1){
						bean.setStatus(2);
					}else{
						bean.setStatus(3);
					}
				}
				bean.setMaiid(fil.getMaiid());
				bean.setId(2);
				filist.add(bean);
			}else if(fil.getType()==3){
				if(fil.getStatus()==1){
					bean.setStatus(fil.getStatus());
				}else{
					if(fil.getPassstatus()==1){
						bean.setStatus(2);
					}else{
						bean.setStatus(3);
					}
				}
				bean.setMaiid(fil.getMaiid());
				bean.setId(3);
				filist.add(bean);
			}else if(fil.getType()==4){
				if(fil.getStatus()==1){
					bean.setStatus(fil.getStatus());
				}else{
					if(fil.getPassstatus()==1){
						bean.setStatus(2);
					}else{
						bean.setStatus(3);
					}
				}
				bean.setMaiid(fil.getMaiid());
				bean.setId(4);
				filist.add(bean);
			}else if(fil.getType()==5){
				if(fil.getStatus()==1){
					bean.setStatus(fil.getStatus());
				}else{
					if(fil.getPassstatus()==1){
						bean.setStatus(2);
					}else{
						bean.setStatus(3);
					}
				}
				bean.setMaiid(fil.getMaiid());
				bean.setId(5);
				filist.add(bean);
			}else if(fil.getType()==6){
				if(fil.getStatus()==1){
					bean.setStatus(fil.getStatus());
				}else{
					if(fil.getPassstatus()==1){
						bean.setStatus(2);
					}else{
						bean.setStatus(3);
					}
				}
				bean.setMaiid(fil.getMaiid());
				bean.setId(5);
				filist.add(bean);
			}
		}
	}
	
	
	
	
	/**
	 * APP打卡
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/insertClockin", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String insertClockin(HttpServletRequest request, Model model) {
		Long date=System.currentTimeMillis();//服务器当前时间
		String msg=null;
		JSONObject jsonObject = null;
//		String sign =null;//身份认证
		String id =null;//用户id
		String type=null;//打卡类型，1:上班1 2:下班1 3:上班2 4:下班2  5:上班3 6:下班3 
		String attendanceid=null;//考勤ID
		int latetime=0;//迟到
		int earlytime=0;//早退
		String apptime=null;//APP打卡时间
		String detailsid=null;//考勤日期表id
		String lat=null;//纬度
		String lon=null;//经度
		String address=null;//地址
		int workingtime=0;//上班时长
		int organizationid=0;//商户id
		String json = request.getParameter("json");
		try {
			json = java.net.URLDecoder.decode(json,"UTF-8");
	    } catch (UnsupportedEncodingException e1) {
	    	e1.printStackTrace();
	    }
		jsonObject = JSONObject.fromObject(json);
		try{
			id =jsonObject.getString("userid");
//			sign =jsonObject.getString("sign");
			type =jsonObject.getString("type");
			apptime =jsonObject.getString("apptime");
			lat =jsonObject.getString("lat");
			lon =jsonObject.getString("lon");
			attendanceid =jsonObject.getString("attendanceid");
			detailsid =jsonObject.getString("detailsid");
			address =jsonObject.getString("address");
			organizationid =jsonObject.getInt("organizationid");
		}catch(Exception e){
            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		try {
			TUser user=userService.selectTUserId(id);
//			if (user == null) {
//				msg="{\"code\":\"2\",\"msg\":\"用户信息有误\"}";
//				return msg;
//			}
//			boolean judge=IdentityController.authentication(user, IdentityController.INSERTCLOCKIN, sign);
//			if(!judge){
//				msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//				return msg;
//			}
			TSchedulingdetails details=schedulingdetailsService.getTSchedulingdetailsById(Integer.valueOf(detailsid));
			if(apptime!=null&&apptime.length()>0){//验证APP时间 是否差距1分钟
				Long apptimelong=Long.valueOf(apptime);
				if(date-apptimelong<=60000&&date-apptimelong>=-60000){
					date=apptimelong;
				}
			}
			/*Long apptimelong=Long.valueOf(apptime);
			Long date = apptimelong;*/
			if(address!=null&&!"".equals(address)){
				address=URLDecoder.decode(address,"UTF-8");
			}
			TClocktime cktim=new TClocktime();
			if(attendanceid!=null&&!"".equals(attendanceid)&&!"0".equals(attendanceid)){
				TAttendance att=attendanceService.selectTAttendanceId(attendanceid);
				if(att!=null){
					if(type.equals("1")){
						for (TClocktime clock : details.getClolist()) {
							if(clock.getSort()==1){
								cktim=clock;
								break;
							}
						}
						if(date>cktim.getTime()){
							latetime=(int) Math.abs((date-cktim.getTime())/60000);
						}
						att.setLat1(Double.valueOf(lat));
						att.setLon1(Double.valueOf(lon));
						att.setStarttime1(date);
						att.setResults1(latetime);
						att.setAddress1(address);
					}else if(type.equals("2")){
						for (TClocktime clock : details.getClolist()) {
							if(clock.getSort()==2){
								cktim=clock;
								break;
							}
						}
						if(date<cktim.getTime()){
							earlytime=(int) Math.abs((date-cktim.getTime())/60000);
						}
						att.setLat2(Double.valueOf(lat));
						att.setLon2(Double.valueOf(lon));
						att.setEndtime1(date);
						att.setResults2(earlytime);
						att.setAddress2(address);
						for (TClocktime clock : details.getClolist()) {
							if(clock.getSort()==1){
								if(earlytime>0){//验证是否早退
									workingtime=(int) Math.abs((date-clock.getTime())/60000);
								}else{
									workingtime=(int) Math.abs((cktim.getTime()-clock.getTime())/60000);
								}
								break;
							}
						}
						att.setWorkingtime(att.getWorkingtime()+workingtime);
					}else if(type.equals("3")){
						for (TClocktime clock : details.getClolist()) {
							if(clock.getSort()==3){
								cktim=clock;
								break;
							}
						}
						if(date>cktim.getTime()){
							latetime=(int) Math.abs((date-cktim.getTime())/60000);
						}
						att.setLat3(Double.valueOf(lat));
						att.setLon3(Double.valueOf(lon));
						att.setStarttime2(date);
						att.setResults3(latetime);
						att.setAddress3(address);
					}else if(type.equals("4")){
						for (TClocktime clock : details.getClolist()) {
							if(clock.getSort()==4){
								cktim=clock;
								break;
							}
						}
						if(date<cktim.getTime()){
							earlytime=(int) Math.abs((date-cktim.getTime())/60000);
						}
						att.setLat4(Double.valueOf(lat));
						att.setLon4(Double.valueOf(lon));
						att.setEndtime2(date);
						att.setResults4(earlytime);
						att.setAddress4(address);
						for (TClocktime clock : details.getClolist()) {
							if(clock.getSort()==3){
								if(earlytime>0){//验证是否早退
									workingtime=(int) Math.abs((date-clock.getTime())/60000);
								}else{
									workingtime=(int) Math.abs((cktim.getTime()-clock.getTime())/60000);
								}
								break;
							}
						}
					}else if(type.equals("5")){
						for (TClocktime clock : details.getClolist()) {
							if(clock.getSort()==5){
								cktim=clock;
								break;
							}
						}
						if(date>cktim.getTime()){
							latetime=(int) Math.abs((date-cktim.getTime())/60000);
						}
						att.setLat5(Double.valueOf(lat));
						att.setLon5(Double.valueOf(lon));
						att.setStarttime3(date);
						att.setResults5(latetime);
						att.setAddress5(address);
					}else if(type.equals("6")){
						for (TClocktime clock : details.getClolist()) {
							if(clock.getSort()==6){
								cktim=clock;
								break;
							}
						}
						if(date<cktim.getTime()){
							earlytime=(int) Math.abs((date-cktim.getTime())/60000);
						}
						att.setLat6(Double.valueOf(lat));
						att.setLon6(Double.valueOf(lon));
						att.setEndtime3(date);
						att.setResults6(earlytime);
						att.setAddress6(address);
						for (TClocktime clock : details.getClolist()) {
							if(clock.getSort()==5){
								if(earlytime>0){//验证是否早退
									workingtime=(int) Math.abs((date-clock.getTime())/60000);
								}else{
									workingtime=(int) Math.abs((cktim.getTime()-clock.getTime())/60000);
								}
								break;
							}
						}
					}
					att.setLatetime(att.getLatetime()+latetime);
					att.setEarlytime(att.getEarlytime()+earlytime);
					attendanceService.updateTAttendance(att);
					msg="{\"code\":\"1\",\"msg\":\"打卡成功\"}";
				}else{
					msg="{\"code\":\"2\",\"msg\":\"获取考勤信息异常\"}";
				}
			}else{
				msg=insertTAttendance(user, details, cktim, type, date, lat, lon, latetime, earlytime, address, workingtime, organizationid,1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msg;
	}
	
	/**
	 * 写入打卡记录
	 * @param user 用户信息
	 * @param details 考勤信息
	 * @param cktim 打卡时间明细
	 * @param type 打卡类型，1:上班1 2:下班1 3:上班2 4:下班2  5:上班3 6:下班3 
	 * @param date 服务器当前时间
	 * @param lat 纬度
	 * @param lon 经度
	 * @param latetime 迟到
	 * @param earlytime 早退
	 * @param address 地址
	 * @param workingtime 上班时长
	 * @param organizationid 归属商户
	 * @param organizationid 创建时间 1：当前系统时间 2：打卡时间
	 * @return
	 */
	public String insertTAttendance(TUser user,TSchedulingdetails details,TClocktime cktim,String type,
			Long date,String lat,String lon,int latetime,int earlytime,String address,int workingtime,int organizationid,
			int difference){
		String msg=null;
		long start=DateUtil.getStartTime(0,date).getTime();
		long end=DateUtil.getnowEndTime(23,date).getTime();
		List<TAttendance> fanat=attendanceService.selectTAttendanceListName(user.getId(), start, end);
		//验证考勤记录是否存在
		if(fanat==null||fanat.size()==0){
			TAttendance att=new TAttendance();
			att.setUserId(user.getId());
			if(type.equals("1")){
				for (TClocktime clock : details.getClolist()) {
					if(clock.getSort()==1){
						cktim=clock;
						break;
					}
				}
				if(date>cktim.getTime()){
					latetime=(int) Math.abs((date-cktim.getTime())/60000);
				}
				att.setLat1(Double.valueOf(lat));
				att.setLon1(Double.valueOf(lon));
				att.setStarttime1(date);
				att.setResults1(latetime);
				att.setAddress1(address);
			}else if(type.equals("2")){
				for (TClocktime clock : details.getClolist()) {
					if(clock.getSort()==2){
						cktim=clock;
						break;
					}
				}
				if(date<cktim.getTime()){
					earlytime=(int) Math.abs((date-cktim.getTime())/60000);
				}
				att.setLat2(Double.valueOf(lat));
				att.setLon2(Double.valueOf(lon));
				att.setEndtime1(date);
				att.setResults2(earlytime);
				att.setAddress2(address);
				for (TClocktime clock : details.getClolist()) {
					if(clock.getSort()==1){
						if(earlytime>0){//验证是否早退
							workingtime=(int) Math.abs((date-clock.getTime())/60000);
						}else{
							workingtime=(int) Math.abs((cktim.getTime()-clock.getTime())/60000);
						}
						break;
					}
				}
			}else if(type.equals("3")){
				for (TClocktime clock : details.getClolist()) {
					if(clock.getSort()==3){
						cktim=clock;
						break;
					}
				}
				if(date>cktim.getTime()){
					latetime=(int) Math.abs((date-cktim.getTime())/60000);
				}
				att.setLat3(Double.valueOf(lat));
				att.setLon3(Double.valueOf(lon));
				att.setStarttime2(date);
				att.setResults3(latetime);
				att.setAddress3(address);
			}else if(type.equals("4")){
				for (TClocktime clock : details.getClolist()) {
					if(clock.getSort()==4){
						cktim=clock;
						break;
					}
				}
				if(date<cktim.getTime()){
					earlytime=(int) Math.abs((date-cktim.getTime())/60000);
				}
				att.setLat4(Double.valueOf(lat));
				att.setLon4(Double.valueOf(lon));
				att.setEndtime2(date);
				att.setResults4(earlytime);
				att.setAddress4(address);
				for (TClocktime clock : details.getClolist()) {
					if(clock.getSort()==3){
						if(earlytime>0){//验证是否早退
							workingtime=(int) Math.abs((date-clock.getTime())/60000);
						}else{
							workingtime=(int) Math.abs((cktim.getTime()-clock.getTime())/60000);
						}
						break;
					}
				}
			}else if(type.equals("5")){
				for (TClocktime clock : details.getClolist()) {
					if(clock.getSort()==5){
						cktim=clock;
						break;
					}
				}
				if(date>cktim.getTime()){
					latetime=(int) Math.abs((date-cktim.getTime())/60000);
				}
				att.setLat5(Double.valueOf(lat));
				att.setLon5(Double.valueOf(lon));
				att.setStarttime3(date);
				att.setResults5(latetime);
				att.setAddress5(address);
			}else if(type.equals("6")){
				for (TClocktime clock : details.getClolist()) {
					if(clock.getSort()==6){
						cktim=clock;
						break;
					}
				}
				if(date<cktim.getTime()){
					earlytime=(int) Math.abs((date-cktim.getTime())/60000);
				}
				att.setLat6(Double.valueOf(lat));
				att.setLon6(Double.valueOf(lon));
				att.setEndtime3(date);
				att.setResults6(earlytime);
				att.setAddress6(address);
				for (TClocktime clock : details.getClolist()) {
					if(clock.getSort()==5){
						if(earlytime>0){//验证是否早退
							workingtime=(int) Math.abs((date-clock.getTime())/60000);
						}else{
							workingtime=(int) Math.abs((cktim.getTime()-clock.getTime())/60000);
						}
						break;
					}
				}
			}
			att.setLatetime(latetime);
			att.setEarlytime(earlytime);
			att.setSchedulingId(user.getSchedulingId());
			if(difference==1){
				att.setCreatetime(System.currentTimeMillis());
			}else{
				att.setCreatetime(date);
			}
			att.setOrganizationId(organizationid);
			int fal=attendanceService.insertTAttendance(att);
			if(fal==1){
				msg="{\"code\":\"1\",\"msg\":\"打卡成功\"}";
			}else{
				msg="{\"code\":\"2\",\"msg\":\"获取考勤信息异常\"}";
			}
		}else{
			msg="{\"code\":\"2\",\"msg\":\"重复打卡\"}";
		}
		return msg;
	}
	
	
	
	
	
	/**
	 * APP获取月历信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getMonthlycalendar", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String getMonthlycalendar(HttpServletRequest request, Model model) {
		Long date=System.currentTimeMillis();//服务器当前时间 
		int nowday=DateUtil.getDay(date);
		int nowmonth=DateUtil.getMonth(date);
		int nowyear=DateUtil.getYear(date);
		String msg=null;
		JSONObject jsonObject = null;
//		String sign =null;//身份认证
		String id =null;//用户id
		int year=0;
		int month=0;
		String time=null;
		long start=0;
		long end=0;
		String json = request.getParameter("json");
		jsonObject = JSONObject.fromObject(json);
		try{
			id =jsonObject.getString("userid");
//			sign =jsonObject.getString("sign");
			year =jsonObject.getInt("year");
			month =jsonObject.getInt("month");
		}catch(Exception e){
            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		try{
			TUser user=userService.selectTUserId(id);
//			if (user == null) {
//				msg="{\"code\":\"2\",\"msg\":\"用户信息有误\"}";
//				return msg;
//			}
//			boolean judge=IdentityController.authentication(user, IdentityController.GETMONTHLYCALENDAR, sign);
//			if(!judge){
//				msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//				return msg;
//			}
			time=year+"-"+month+"-01";
			long starttime=DateUtil.getFirstDayOfMonth(time);
			long endtime=DateUtil.getLastDayOfMonth(time);
			List<TSchedulingdetails> chelist=schedulingdetailsService.getTSchedulingdetailsList(year, month, 0, user.getSchedulingId());
			List<TAttendance> attlist=attendanceService.selectTAttendanceListName(user.getId(), starttime, endtime);
			SchedulingAppBean app=new SchedulingAppBean();
			TAttendanceAppBean attapp=new TAttendanceAppBean();
			TSchedulingdetails tails=new TSchedulingdetails();
			if(chelist!=null){
				if(attlist!=null&&attlist.size()>0){
					BeanUtils.copyProperties(attapp,attlist.get(0));
					app.setAttendance(attapp);
				}
				for (TSchedulingdetails che : chelist) {
					if(che.getClolist()!=null&&che.getClolist().size()>0){
						start=DateUtil.getStartTime(0,che.getClolist().get(0).getTime()).getTime();
						end=DateUtil.getnowEndTime(23,che.getClolist().get(che.getClolist().size()-1).getTime()).getTime();
						for (TAttendance att : attlist) {
							if(att.getCreatetime()>=start&&att.getCreatetime()<=end){
								if(che.getClolist().size()==2){
									if(att.getResults1()==0&&att.getStarttime1()!=null&&att.getResults2()==0&&att.getEndtime1()!=null){
										che.setVerification(true);
									}
								}else if(che.getClolist().size()==4){
									if(att.getResults1()==0&&att.getStarttime1()!=null&&att.getResults2()==0&&att.getEndtime1()!=null
											&&att.getResults3()==0&&att.getStarttime2()!=null&&att.getResults4()==0&&att.getEndtime2()!=null){
										che.setVerification(true);
									}
								}else if(che.getClolist().size()==6){
									if(att.getResults1()==0&&att.getStarttime1()!=null&&att.getResults2()==0&&att.getEndtime1()!=null
											&&att.getResults3()==0&&att.getStarttime2()!=null&&att.getResults4()==0&&att.getEndtime2()!=null
											&&att.getResults5()==0&&att.getStarttime3()!=null&&att.getResults6()==0&&att.getEndtime3()!=null){
										che.setVerification(true);
									}
								}
							}
						}
					}
					if(che.getYear()<nowyear){
						setSchedulingdetails(tails, che, app);
					}else if(che.getYear()==nowyear){
						if(che.getMonth()<nowmonth){
							setSchedulingdetails(tails, che, app);
						}else if(che.getMonth()==nowmonth){
							if(che.getDay()<=nowday){
								setSchedulingdetails(tails, che, app);
							}
						}
					}
				}
			}
			Map<String, Object> datemap=new HashMap<String, Object>();
			datemap.put("data", app);
			datemap.put("code", "1");
			JSONObject jsons = JSONObject.fromObject(datemap);
			msg=jsons.toString();
		}catch(Exception e){
			e.printStackTrace();
		}
		return msg;
	}
	
	public void setSchedulingdetails(TSchedulingdetails tails,TSchedulingdetails che,SchedulingAppBean app){
		tails=new TSchedulingdetails();
		tails.setDay(che.getDay());
		tails.setId(che.getId());
		tails.setMonth(che.getMonth());
		tails.setYear(che.getYear());
		tails.setSchedulingId(che.getSchedulingId());
		tails.setVerification(che.isVerification());
		app.getDetalist().add(tails);
	}
	
	
	/**
	 * APP根据年月日获取打卡信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getYearMonthDay", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String getYearMonthDay(HttpServletRequest request, Model model) {
		long currenttime=System.currentTimeMillis();
		String msg=null;
		JSONObject jsonObject = null;
//		String sign =null;//身份认证
		String id =null;//用户id
		int year=0;
		int month=0;
		int day=0;
		String time=null;
		String json = request.getParameter("json");
		try {
			json = java.net.URLDecoder.decode(json,"UTF-8");
	    } catch (UnsupportedEncodingException e1) {
	    	e1.printStackTrace();
	    }
		jsonObject = JSONObject.fromObject(json);
		try{
			id =jsonObject.getString("userid");
//			sign =jsonObject.getString("sign");
			year =jsonObject.getInt("year");
			month =jsonObject.getInt("month");
			day =jsonObject.getInt("day");
		}catch(Exception e){
			msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
			return msg;
		}
		try{
			TUser user=userService.selectTUserId(id);
//			if (user == null) {
//				msg="{\"code\":\"2\",\"msg\":\"用户信息有误\"}";
//				return msg;
//			}
//			boolean judge=IdentityController.authentication(user, IdentityController.GETYEARMONTHDAY, sign);
//			if(!judge){
//				msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//				return msg;
//			}
			time=year+"-"+month+"-"+day;
			long data=DateUtil.getStringTime(time, "yyyy-MM-dd");
			long starttime=DateUtil.getStartTime(0,data).getTime();
			long endtime=DateUtil.getnowEndTime(23,data).getTime();
			TAttendance att=attendanceService.selectTAttendanceById(user.getId(), starttime, endtime);
			TSchedulingdetails sheToday=schedulingdetailsService.getTSchedulingdetailsAsc(year, month, day,user.getSchedulingId());
			List<TLeave> leavelist=leaveService.getTLeaveList(starttime, endtime, user.getId());
			SchedulingAppBean sappbean=new SchedulingAppBean();
			TAttendanceAppBean attapp=new TAttendanceAppBean();
			List<FillcardAppBean> filist=new ArrayList<FillcardAppBean>();
			List<TFillcard> fillist=new ArrayList<TFillcard>();
			if(att!=null){
				BeanUtils.copyProperties(attapp,att);
				//获取用户补卡审批单信息
				fillist=fillcardService.getTFillcardListByAttid(user.getId(), attapp.getId(),starttime,endtime);
				if(fillist==null||fillist.size()==0){
					fillist=fillcardService.getTFillcardListByAttid(user.getId(), 0,starttime,endtime);
				}
				setTFillcard(fillist,filist);
			}else{
				fillist=fillcardService.getTFillcardListByAttid(user.getId(), 0,starttime,endtime);
				String filltime=null;
				String dataary=DateUtil.getStringFormat(data,"yyyy-MM-dd");
				List<TFillcard> fillistary=new ArrayList<TFillcard>();
				for (TFillcard fil : fillist) {
					filltime=DateUtil.getStringFormat(fil.getFilltime(),"yyyy-MM-dd");
					if(dataary.equals(filltime)){
						fillistary.add(fil);
					}
				}
				setTFillcard(fillistary,filist);
			}
			setFillstatus(currenttime, sheToday.getClolist(), att, filist);
			attapp.setFilist(filist);
			ClocktimeAppBean clockt=null;
			for (TClocktime clo : sheToday.getClolist()) {
				clockt=new ClocktimeAppBean();
				BeanUtils.copyProperties(clockt, clo);
				sappbean.getClocktime().add(clockt);
				setLesveAttendance(clo, leavelist, attapp);
			}
			sappbean.setDetailsid(sheToday.getId());
			sappbean.setAttendance(attapp);
			Map<String, Object> datemap=new HashMap<String, Object>();
			datemap.put("data", sappbean);
			datemap.put("code", "1");
			JSONObject jsons = JSONObject.fromObject(datemap);
			msg=jsons.toString();
		}catch(Exception e){
			e.printStackTrace();
		}
		return msg;
	}
	
	
	
	/**
	 * 封装请假考勤信息
	 * @param clol
	 * @param leavelist
	 * @param attapp
	 */
	public void setLesveAttendance(TClocktime clo,List<TLeave> leavelist,TAttendanceAppBean attapp){
		LeaveAppBean app=new	LeaveAppBean(); 
		for (TLeave leave : leavelist) {
			if(leave.getStarttime()<=clo.getTime()&&leave.getEndtime()>=clo.getTime()){
				app=new LeaveAppBean();
				app.setId(clo.getSort());
				app.setType(leave.getType());
				attapp.getLeavelist().add(app);
			}
		}
		
	}
	
}
